package controller

import (
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"strconv"

	"github.com/beego/beego/v2/core/logs"
	"github.com/gin-gonic/gin"

	"2106a-zg5/demo/order/order_api/global"
	"2106a-zg5/demo/order/order_api/utils"
	"2106a-zg5/demo/order/order_srv/proto"
	util "2106a-zg5/demo/order/order_srv/utils"
)

// CreateOrder 创建订单
func CreateOrder(c *gin.Context) {
	userId := c.PostForm("user_id")
	atoiUserId, _ := strconv.Atoi(userId)
	godosId := c.PostForm("goods_id")
	atoiGoodsId, _ := strconv.Atoi(godosId)
	godosnum := c.PostForm("goods_num")
	atoiGoodsNum, _ := strconv.Atoi(godosnum)
	res, err := global.OrderService.OrderAdd(context.Background(), &proto.OrderAddReq{
		UserId:      int64(atoiUserId),
		MerchantId:  46546,
		GoodsId:     int64(atoiGoodsId),
		GoodsNum:    int64(atoiGoodsNum),
		PayType:     1,
		ShipAddress: "上海八维",
	})
	if err != nil {
		c.JSON(http.StatusOK, &gin.H{
			"message": err.Error(),
			"status":  http.StatusBadRequest,
		})
		return
	}
	c.JSON(http.StatusOK, &gin.H{
		"message": "订单创建成功，请支付",
		"status":  http.StatusOK,
		"data": map[string]interface{}{
			"PayAddress": res.PayAddress,
			"data":       res.Order,
		},
	})
}

// QueryOrder  查询订单
func QueryOrder(c *gin.Context) {}

// ReturnURL 同步回调
func ReturnURL(c *gin.Context) {
	c.JSON(http.StatusOK, &gin.H{
		"message": "成功",
		"data":    "200",
	})
	return
}

// NotifyURL 异步回调
func NotifyURL(c *gin.Context) {
	c.Request.ParseForm()
	data := c.Request.Form
	//fmt.Println(data)
	//logs.Info(data)
	jsD, _ := json.Marshal(data)
	utils.Logs("./pay.log", string(jsD))

	orderNo, i, err := util.Returns(data)
	if err != nil {

		logs.Info(err)
		c.JSON(http.StatusOK, &gin.H{
			"message": err.Error(),
			"data":    "202",
		})
		return
	}
	o, _ := strconv.Atoi(orderNo)
	logs.Info(orderNo, i)
	res, err := global.OrderService.OrderPayStatus(context.Background(), &proto.PayStatusReq{
		OrderNo:   int64(o),
		PayStatus: int64(i),
	})
	if err != nil {
		c.JSON(http.StatusOK, &gin.H{
			"message": err.Error(),
			"data":    "202",
		})
		return
	}
	fmt.Println(res)
}
